package com.vast.ui.component.providers;

import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.swt.SWT;

import com.vast.ui.component.models.Item;
import com.vast.ui.component.models.ItemArray;
import com.vast.ui.component.socketinterface.listner.ISendListener;
import com.vast.ui.component.socketinterface.protocol.VaSTUIComponentProtocol;
import com.vast.ui.component.socketinterface.request.Request;

public class IoEditingSupport extends EditingSupport {
	private CellEditor editor;
	private final int columnIndex;
	private final  ListenerList sendListenerList;
	
	public IoEditingSupport(ColumnViewer viewer, int columnIndex) {
		super(viewer);
		// TODO Auto-generated constructor stub
		editor = new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
		this.columnIndex = columnIndex;
		sendListenerList = new ListenerList();
	}

	@Override
	protected boolean canEdit(Object element) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected CellEditor getCellEditor(Object element) {
		// TODO Auto-generated method stub
		return editor;
	}

	@Override
	protected Object getValue(Object element) {
		// TODO Auto-generated method stub
		ItemArray itemArray = (ItemArray)element;
		Item      item      = itemArray.getItem(columnIndex);
		return    item.isChecked();
	}

	@Override
	protected void setValue(Object element, Object value) {
		// TODO Auto-generated method stub
		//if(columnIndex != 0) {
			ItemArray itemArray  = (ItemArray)element;
			Item      item       = itemArray.getItem(columnIndex);
			item.setChecked(((Boolean) value).booleanValue());
			getViewer().update(element, null);
			
			int packetSize = 14;
			Request request = new Request(packetSize);
			request.writeShort(packetSize);
			request.writeShort(VaSTUIComponentProtocol.PK_IO_UPDATE);
			request.writeInt(itemArray.getLineNumber());
			request.writeInt(item.getValue());
			request.writeShort(VaSTUIComponentProtocol.PK_SOCKET_TERMINATE);
		    
		//}
	}
	
	public void addSendListener(ISendListener listener){
		sendListenerList.add(listener);
	}
	
	public void removeSendListener(ISendListener listener){
		sendListenerList.remove(listener);
	}
}

